package com.alibaba.aliper.agent.sys;

import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.alibaba.aliper.agent.util.FileReader;

public class MemState {
	public MemState(){
		String content = FileReader.readFromFile(MEM_STATE_FILE);
		this.memTotal = this.parse("MemTotal",content);
		this.memFree = this.parse("MemFree", content);
		this.memShared = this.parse("MemShared", content);
	}
	private static HashMap<String,Pattern> patternMap = new HashMap<String, Pattern>();
	private int parse(String field, String content) {
		Pattern pattern = getPattern(field);
		Matcher matcher = pattern.matcher(content);
	    if(matcher.find()){
	    	return Integer.parseInt(matcher.group(1));
	    }
		return 0;
	}
	private static Pattern getPattern(String field) {
		if(patternMap.containsKey(field)){
			return patternMap.get(field);
		} else {
			Pattern pattern = Pattern.compile(field+":\\s+([0-9]+)");
			patternMap.put(field, pattern);
			return pattern;
		}
	}
	public static final String MEM_STATE_FILE="/proc/meminfo";
	private int memTotal;
	private int memFree;
	private int memShared;
	private int buffers;
	private int cached;
	private int swapCached;
	private int active;
	private int activeAnon;
	private int activeCache;
	private int inact_dirty;
	private int inact_laundry;
	private int inact_clean;
	private int inact_target;
	private int highTotal;
	private int highFree;
	private int lowTotal;
	private int lowFree;
	private int swapTotal;
	private int swapFree;
	private int committed_AS;
	public int getMemTotal() {
		return memTotal;
	}
	public int getMemFree() {
		return memFree;
	}
	public int getMemShared() {
		return memShared;
	}
	public int getBuffers() {
		return buffers;
	}
	public int getCached() {
		return cached;
	}
	public int getSwapCached() {
		return swapCached;
	}
	public int getActive() {
		return active;
	}
	public int getActiveAnon() {
		return activeAnon;
	}
	public int getActiveCache() {
		return activeCache;
	}
	public int getInact_dirty() {
		return inact_dirty;
	}
	public int getInact_laundry() {
		return inact_laundry;
	}
	public int getInact_clean() {
		return inact_clean;
	}
	public int getInact_target() {
		return inact_target;
	}
	public int getHighTotal() {
		return highTotal;
	}
	public int getHighFree() {
		return highFree;
	}
	public int getLowTotal() {
		return lowTotal;
	}
	public int getLowFree() {
		return lowFree;
	}
	public int getSwapTotal() {
		return swapTotal;
	}
	public int getSwapFree() {
		return swapFree;
	}
	public int getCommitted_AS() {
		return committed_AS;
	}

}
